package Login;

import Dao.communityDao;
import Dao.communityDaoImpl;
import been.User;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.sql.SQLException;

@WebServlet(name = "LoginServlet",value = "/Login-community")
public class LoginServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action = request.getParameter("action");
        if(action.equals("register")){
            request.getRequestDispatcher("/WEB-INF/Login/register.jsp").forward(request,response);
        }else if(action.equals("returnLogin")){
            request.getRequestDispatcher("/WEB-INF/Login/Login.jsp").forward(request,response);
        }
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        communityDao dao = new communityDaoImpl();
        User user = null;
        String message = null;
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        if (username==null||username.isEmpty() || password==null||password.isEmpty()) {
            message="账号或密码不能为空";
            request.setAttribute("message",message);
            request.getRequestDispatcher("/WEB-INF/Login/Login.jsp").forward(request,response);
        }
        try {
            user=dao.findUserByUsername(username);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        if(user!=null&&user.getPassword().equals(password)) {
            HttpSession session = request.getSession();
            session.setAttribute("user",username);
            if(user.getRole().equals("admin")) {
                request.getRequestDispatcher("/WEB-INF/Login/user.jsp").forward(request,response);
            }
            else
            {
                request.getRequestDispatcher("/WEB-INF/Login/admin.jsp").forward(request,response);
            }

        }
        else{
            message="账号或密码错误";
            request.setAttribute("message",message);
            request.getRequestDispatcher("/WEB-INF/Login/Login.jsp").forward(request,response);
        }

    }
}
